package com.ruoyi.libb.utlis;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

public class SendmailUtli {

	public static void sendmail(String mailbox)throws MessagingException, GeneralSecurityException, UnsupportedEncodingException {

		Properties props = new Properties();
		// 设置邮件服务器 QQ:smtp.qq.com    163:smtp.163.com
		props.setProperty("mail.smtp.host", "smtp.qq.com");
		// 设置是否需要验证用户名
		props.setProperty("mail.smtp.auth", "true");

		// 如果是QQ邮箱，还要设置SSL加密，加上以下代码即可
		MailSSLSocketFactory sf = new MailSSLSocketFactory();
		sf.setTrustAllHosts(true);
		props.put("mail.smtp.ssl.enable", "true");
		props.put("mail.smtp.ssl.socketFactory", sf);

		/**
		 * 发送邮件三步骤
		 */

		// 1、创建定义整个应用程序所需的环境信息的Session 对象
		Session session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// 发件人邮件用户名、授权码
				return new PasswordAuthentication("704976433@qq.com", "quunvcgsfsefebdg");
			}
		});
		// 开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
		session.setDebug(true);

		// 2、创建邮件对象
		MimeMessage message = new MimeMessage(session);
		// 发件人
		message.setFrom(new InternetAddress("704976433@qq.com"));
		//查看要发送的邮箱是qq还是网易
		String substring = mailbox.substring(mailbox.length()-6, mailbox.length()-4);
		if (substring.equals("qq")){
			// 指定抄送人
			message.setRecipients(Message.RecipientType.CC, mailbox);
		}else {
			// 指定收件人
		message.setRecipients(Message.RecipientType.TO, mailbox);
		}
		// 设置邮件主题
		message.setSubject("带图片的信息");


		BodyPart messageBodyPart = new MimeBodyPart();

		// 描述数据关系: 附件+(文本+图片)
		String filename = "D:\\合同\\个人借款合同1.pdf";
		String receiveName = "个人借款合同1.pdf";
		DataSource source = new FileDataSource(filename);
		messageBodyPart.setDataHandler(new DataHandler(source));
		messageBodyPart.setFileName(MimeUtility.encodeText(receiveName));

		MimeMultipart allFile =new MimeMultipart("mixed");
		allFile.addBodyPart(messageBodyPart); // 附件一


		// 封装Message消息，保存修改
		message.setContent(allFile);
		message.saveChanges();
		// 设置发送时间
		message.setSentDate(new Date());

		// 3、发送邮件,调用Transport.send静态方法发送Message对象中的邮件消息内容
		Transport.send(message);

	}



}
